#!/usr/bin/python
'''
Created by Colin Gillespie <c.gillespie@ncl.ac.uk>
Last Changed on: $LastChangedDate: 2008-03-07 09:58:07 +0000 (Fri, 07 Mar 2008) $

Work in progress
'''

__revision__ = '$Rev: 58 $'

from copy import copy
import os
import libsbml


#Import non-standard modules


class GetEvents(object):
    ''''''
        
    def __init__(self, model):
        self.m = model

    def __clearFormula(self):
        self.formula = []
        
    def getEvents(self):
        ev_dict = {}
        for i, event in enumerate(self.m.getListOfEvents()):
            ev_dict[event.getId()] = {}
            ev = ev_dict[event.getId()]
            
            ev['trigger'] = self.getTrigger(event)
            ev['assignments'], ev['values'] = self.getEventAssignments(event)
        ordered_event_ids = []
        ordered_event_times = []
        for event in ev_dict.keys():
            time = ev_dict[event]['trigger'][2]
            print ordered_event_times
            index = self.__addToOrderedList(ordered_event_times, time)
            print index, event,time,'XXXX'
            #import sys
            #sys.exit()
            ordered_event_ids.insert(index, event)
        print ordered_event_ids, ordered_event_times
        return ev_dict, ordered_event_ids
    
    def __addToOrderedList(self, ordered, time):
        if not len(ordered):
            ordered.append(time)
            return 0
        
        for t in ordered:
            if time < t:
                index = ordered.index(t)
                ordered.insert(index, time)
                return index
        return len(ordered)


    def getTrigger(self, event):
        '''
        '''
        self.__clearFormula()
        self.walktree(event.getTrigger().getMath())
        return self.formula
 

    
    def getEventAssignments(self, event):
        assignments = []
        values = []
        for assignment in event.getListOfEventAssignments():
            self.__clearFormula()
            self.walktree(assignment.getMath())
            assignments.append(assignment.getVariable())
            values.append(self.formula[0])
        
        return assignments,values
    
    def walktree(self, tree):
        ''' '''
        if not tree: 
            return
        
        self.walktree(tree.getLeftChild())
        if tree.isName() or tree.isRelational():
            self.formula.append(tree.getName())
        
        #print dir(tree)
        if tree.isReal():
            self.formula.append(tree.getReal())
        
        self.walktree(tree.getRightChild())

        
        
        
        
        
